/**
 * 用户管理模块
 */
const router = require('koa-router')();
const jwt = require('../utils/jwt');
const roleDB = require('../models/roleSchema');
const util = require('../utils/util');
const md5 = require('md5');

router.prefix('/role');

// 查询所有的角色列表
router.get('/allList', async (ctx) => {
  try {
    let list = await roleDB.find({}, '_id roleName');
    ctx.body = util.success(list);
  } catch (error) {
    ctx.body = util.fail(`查询失败：${error.stack}`);
  }
});

// 分页 查询所有的角色列表
router.get('/list', async (ctx) => {
  let { roleName } = ctx.request.query;
  let { page, skipIndex } = util.pager(ctx.request.query);
  let params = {};
  if (roleName) params.roleName = roleName;

  try {
    let list = await roleDB.find(params).skip(skipIndex).limit(page.pageSize);
    const total = await roleDB.countDocuments(params);
    ctx.body = util.success({ list, page: { ...page, total } });
  } catch (error) {
    ctx.body = util.fail(`查询失败：${error.stack}`);
  }
});

// 角色的操作  add edit delete
router.post('/operate', async (ctx) => {
  let { _id, action, ...params } = ctx.request.body;
  let res, info;
  try {
    if (action == 'add') {
      res = await roleDB.create(params);
      info = '创建成功';
      ctx.body = util.success(res, info);
    } else if (action == 'edit') {
      if (_id) {
        params.updateTime = Date.now();
        res = await roleDB.findByIdAndUpdate(_id, params);
        info = '编辑成功';
        ctx.body = util.success(res, info);
      } else {
        ctx.body = util.failParam();
      }
    } else if (action == 'delete') {
      if (_id) {
        res = await roleDB.findByIdAndRemove(_id);
        info = '删除成功';
        ctx.body = util.success(res, info);
      } else {
        ctx.body = util.failParam();
      }
    } else {
      ctx.body = util.failParam();
    }
  } catch (error) {
    ctx.body = util.fail(`请求失败：${error.stack}`);
  }
});

// 权限设置
router.post('/permission', async (ctx) => {
  let { _id, ...params } = ctx.request.body;

  try {
    params.updateTime = Date.now();
    await roleDB.findByIdAndUpdate(_id, params);
    info = '权限设置成功';
    ctx.body = util.success({}, info);
  } catch (error) {
    ctx.body = util.fail(`更新失败：${error.stack}`);
  }
});

module.exports = router;
